<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * 码上借 场所码
 */
class CodePlace extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'code_place';



    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 开始时间(开始)
     * @param end_time datetime 开始时间(截止)
     */
    public function lists($keywords, $start_time = null, $end_time = null, $is_play = null, $limit = 10)
    {
        $res = $this->where(function ($query) use ($keywords) {
            if ($keywords) {
                $query->where('name', 'like', "%$keywords%");
            }
        })->where(function ($query) use ($is_play, $start_time, $end_time) {
            if ($is_play) {
                $query->where('is_play', $is_play);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }


    /**
     * 判断是否在合理范围内
     */
    public function checkPlaceCodeDistance($qr_code, $lon, $lat)
    {
        $getPlaceCodeInfo = $this->getPlaceCodeInfo($qr_code);
        if (empty($getPlaceCodeInfo)) {
            return '请扫描正确的场所码';
        }
        if ($getPlaceCodeInfo['is_play'] != 1) {
            return '此场所码管理员已关闭，详情请咨询管理员';
        }


        $code_borrow_valid_range = $getPlaceCodeInfo['distance'] ? $getPlaceCodeInfo['distance'] : config('other.code_borrow_valid_range');
        //计算距离
        $distance = get_distance($getPlaceCodeInfo['lon'], $getPlaceCodeInfo['lat'], $lon, $lat);
        if ($distance > $code_borrow_valid_range) {

            Log::error("ID：" . $qr_code);
            Log::error("经纬度：" . $lon . '~' . $lat);
            Log::error('设置范围：' . $code_borrow_valid_range);
            Log::error("当前距离：" . $distance);

            return '当前位置不在管理员设置的范围内';
        }
        Log::error("ID：" . $qr_code);
        Log::error("经纬度：" . $lon . '~' . $lat);
        Log::error('设置范围：' . $code_borrow_valid_range);
        Log::error("当前距离：" . $distance);
       
        return true;
    }



    /**
     * 根据 二维码 编号，获取场所码信息
     * @param qr_code
     */
    public function getPlaceCodeInfo($qr_code, $field = [])
    {
        if (substr($qr_code, 0, 2) != 22) {
            return false; //不是正规二维码
        }
        if (empty($field)) {
            $field = ['id', 'name', 'distance', 'lon', 'lat', 'qr_code', 'qr_url', 'is_play'];
        }
        $data = $this->select($field)->where('qr_code', $qr_code)->where('is_del', 1)->first();
        return $data;
    }
}
